<?php

defined('_JEXEC') or die;

class DoskaModelCategory extends JModelAdmin {
	
	public function getForm($data = array(), $loadData = true) {
		
		$form = $this->loadForm(
								$this->option.".category",
								"category",
								array('control' => 'jform', 'load_data' => $loadData));
		
		if (empty($form))
	    {
	        return false;
	    }
	 
	    return $form;
	}
	
	public function getTable($type = 'Category', $prefix = 'DoskaTable', $config = array())
	{
		return JTable::getInstance($type, $prefix, $config);
	}
	
	
	protected function loadFormData()
	{
		$data = JFactory::getApplication()->getUserState(
			'com_doska.edit.category.data',
			array()
		);
		
 
		if (empty($data))
		{
			$data = $this->getItem();
		}

		return $data;
	}
	
	
	
	public function save($data) {
	
		if(!trim($data['name'])) {
			$this->setError(JText::_('COM_DOSKA_WARNING_PROVIDE_VALID_NAME'));
			return FALSE;
		}
		
		if(trim($data['alias']) == '') {
			$data['alias'] = $data['name'];
			$data['alias'] = JApplicationHelper::stringURLSafe($data['alias']);
		}
		
		
		if(parent::save($data)) {
			return TRUE;
		}
		return FALSE;
		
	}
	
	
	
	/**
	 * Saves the manually set order of records.
	 *
	 * @param   array    $pks    An array of primary key ids.
	 * @param   integer  $order  +1 or -1
	 *
	 * @return  mixed
	 *
	 * @since   12.2
	 */
	public function saveorder($pks = null, $order = null)
	{
		$table = $this->getTable();
		$tableClassName = get_class($table);
		$contentType = new JUcmType;
		$type = $contentType->getTypeByTable($tableClassName);
		$tagsObserver = $table->getObserverOfClass('JTableObserverTags');
		$conditions = array();

		if (empty($pks))
		{
			return JError::raiseWarning(500, JText::_($this->text_prefix . '_ERROR_NO_ITEMS_SELECTED'));
		}

		// Update ordering values
		foreach ($pks as $i => $pk)
		{
			$table->load((int) $pk);

			// Access checks.
			if (!$this->canEditState($table))
			{
				// Prune items that you can't change.
				unset($pks[$i]);
				JLog::add(JText::_('JLIB_APPLICATION_ERROR_EDITSTATE_NOT_PERMITTED'), JLog::WARNING, 'jerror');
			}
			elseif ($table->ordering != $order[$i])
			{
				$table->ordering = $order[$i];

				if ($type)
				{
					$this->createTagsHelper($tagsObserver, $type, $pk, $type->type_alias, $table);
				}

				if (!$table->store())
				{
					$this->setError($table->getError());

					return false;
				}

			}
		}


		// Clear the component's cache
		$this->cleanCache();

		return true;
	}
	
	

}
